package com.example.shop.service.impl;

import com.example.shop.domain.Product;
import com.example.shop.exception.ShopException;
import com.example.shop.repository.ProductRepository;
import com.example.shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Override
    public Product findOne(String productId) {
        return productRepository.findOne(productId);
    }

    @Override
    public Product save(Product product) {
        return productRepository.save(product);
    }

    @Override
    public List<Product> findAll() {
        return productRepository.findAll();
    }

    @Override
    @Transactional
    public void increaseStock(Product product, Integer quantity) {

        Integer result = product.getStock() + quantity;
        product.setStock(result);
        productRepository.save(product);

    }

    @Override

    public void decreaseStock(Product product, Integer quantity) {

        Integer result = product.getStock()-quantity;
        if(result<0){
            throw new ShopException("库存不足");
        }
        product.setStock(result);
        productRepository.save(product);
    }
}
